<!-- 房屋管理 -->
<template>
  <div>
    <div class="header">
      <div class="title">
        <div style="margin-bottom: 15px; margin-top: 15px">
          <a-space style="margin-left: 10px">
            <span>开始时间：</span>
            <a-date-picker v-model:value="startDate" :format="dateFormat" :disabledDate="disabledFutureDate"  />
          </a-space>
          <a-space style="margin-left: 10px">
            <span>结束时间：</span>
            <a-date-picker v-model:value="endDate" :format="dateFormat" :disabledDate="disabledFutureDate"  />
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <a-space class="search-btn">
            <a-button type="primary" @click="searchBtn">查询</a-button>
          </a-space>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <space style="float: right; margin-right: 10px">
            <a-button type="primary" @click="handleExport"> 导出统计表 </a-button>
          </space>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <space style="float: right; margin-right: 10px">
            <a-button type="primary" @click="handleExport"> 导出明细 </a-button>
          </space>
        </div>
      </div>
      <div style="width: 100%; background: #fff; height: 40px">
        <div style="width: 45%; float: left; font-size: 16px; padding-left: 20px; line-height: 37px"
          ><home-outlined two-tone-color="#eb2f96" /><span style="padding: 0px 10px">
            {{ currentTitle }}</span
          ></div
        >
        <div
          style="
            width: 30%;
            float: right;
            font-size: 16px;
            padding-left: 20px;
            line-height: 37px;
            text-align: right;
            padding-right: 20px;
          "
          ><a style="color: blue" @click="getBack"
            ><arrow-left-outlined two-tone-color="#eb2f96" style="padding: 0px 10px" />返回上一页</a
          ></div
        >
      </div>
      <a-table
        :dataSource="tableData"
        :columns="displayColumns"
        :pagination="false"
        :scroll="{ x: 1500, y: tableHeight }"
        bordered
        :loading="loading"
      >
        <!-- vue3 中的写法 -->
        <template #headerCell="{ column }">
          <template v-if="column.key == 'xzq'">
            <Tooltip placement="top">
              <template #title>
                <span>区县名称</span>
              </template>
              <span>区县名称 </span>
            </Tooltip>
          </template>

          <template v-if="column.key == 'zcount'">
            <Tooltip placement="top">
              <template #title>
                <span>房屋总数（栋）</span>
              </template>
              <span> 房屋总数（栋） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zccount'">
            <Tooltip placement="top">
              <template #title>
                <span>检查数量（栋）</span>
              </template>
              <span> 检查数量（栋） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zcl'">
            <Tooltip placement="top">
              <template #title>
                <span>检查率</span>
              </template>
              <span> 检查率 </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'yhcount'">
            <Tooltip placement="top">
              <template #title>
                <span>隐患数量（个）</span>
              </template>
              <span> 隐患数量（个） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zgcount'">
            <Tooltip placement="top">
              <template #title>
                <span>整改数量（个）</span>
              </template>
              <span> 整改数量（个） </span>
            </Tooltip>
          </template>
        </template>
      </a-table>
      
    </div>
  </div>
</template>

<script lang="ts" setup>
  import moment from 'moment';
  import dayjs from 'dayjs';
  import { ref, reactive, toRefs, onMounted, onBeforeMount, computed } from 'vue';
  import { getCheckVillageProgress } from '/@/api/demo/system'; //统计工作进展
  import { useUserStore } from '/@/store/modules/user';
  import { iTableData, iTableColumns } from './types/table';
  import { iParams } from './types/params';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useCheckStore } from '/@/store/modules/checkStore';
  import { useRouter,useRoute } from 'vue-router';

  const disabledFutureDate = (current) => {
  return current && current > moment().endOf('day');
};
  const userStore = useUserStore();
    const route = useRoute();
  const {  xzqdm,towndm, startTime, endTime, currentTitle } =
    route.query;
  const store = useCheckStore();
  const globSetting = useGlobSetting();
  let userInfo = ref<any>(null);
  const visible = ref(false);
  let detailTableHeight = ref<number>(0); // 表格高度
  let tableHeight = ref<number>(0); // 表格高度
  let pageIndex = ref(1);
  let pageSize = ref(20);
  const dateFormat = 'YYYY-MM-DD';
  const startDate = ref<any>(null); // 开始时间
  const endDate = ref<any>(null); // 结束时间
  const strXzqdm = ref<string[]>([]);
  const router = useRouter();
  let regionList = ref<any[]>([]);
  let data = reactive<{
    tableData: iTableData[];
    tableColumns: iTableColumns[];
    wscolsList: { wch: number }[];
    id: number | any;
    loading: Boolean;
    keyWorld: String;
    currentqx: string; // 当前行政区名称
    cityToken: string | any;
    startTime: string; // 开始时间
    endTime: string; // 结束时间
  }>({
    // 表格数据
    tableData: [],
    tableColumns: [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        align: 'center',
        width: 130,
      },
      {
        title: '名称',
        dataIndex: 'village',
        key: 'village',
        align: 'center',
        width: 170,
      },
      {
        title: '房屋总数(栋)',
        dataIndex: 'zcount',
        key: 'zcount',
        align: 'center',
        width: 170,
      },
      {
        title: '检查数量（栋）',
        dataIndex: 'jccount',
        key: 'jccount',
        align: 'center',
        width: 170,
		  customCell: (row, index, column) => {
          let isNoHzyh = row.village !== '汇总' ? true : false;
          let style = 'cursor:pointer;text-decoration: underline; color: blue;';
          let isNoZero = row[column.key] !== 0 ? true : false;
          return {
            style: `${isNoHzyh === true && isNoZero ? style : ''}`,
            class: 'cell-hover',
            onClick: async () => {
              getDetailData_1(row, index, column, isNoHzyh, isNoZero);
            },
          };
        },
      },
      {
        title: '未检查数量（栋）',
        dataIndex: 'wjccount',
        key: 'wjccount',
        align: 'center',
        width: 170,
		  customCell: (row, index, column) => {
          let isNoHzyh = row.village !== '汇总' ? true : false;
          let style = 'cursor:pointer;text-decoration: underline; color: blue;';
          let isNoZero = row[column.key] !== 0 ? true : false;
          return {
            style: `${isNoHzyh === true && isNoZero ? style : ''}`,
            class: 'cell-hover',
            onClick: async () => {
              getDetailData_2(row, index, column, isNoHzyh, isNoZero);
            },
          };
        },
      },
      {
        title: '检查率',
        dataIndex: 'jcl',
        key: 'jcl',
        align: 'center',
        width: 170,
      },
      {
        title: '隐患数量（个）',
        dataIndex: 'yhcount',
        key: 'yhcount',
        align: 'center',
        width: 170,
		  // customCell: (row, index, column) => {
      //     let isNoHzyh = row.xzq !== '汇总' ? true : false;
      //     let style = 'cursor:pointer;text-decoration: underline; color: blue;';
      //     let isNoZero = row[column.key] !== 0 ? true : false;
      //     return {
      //       style: `${isNoHzyh === true && isNoZero ? style : ''}`,
      //       class: 'cell-hover',
      //       onClick: async () => {
      //         getDetailData_3(row, index, column, isNoHzyh, isNoZero);
      //       },
      //     };
      //   },
      },
      {
        title: '整改数量（个）',
        dataIndex: 'zgcount',
        key: 'zgcount',
        align: 'center',
        width: 170,
		  // customCell: (row, index, column) => {
      //     let isNoHzyh = row.xzq !== '汇总' ? true : false;
      //     let style = 'cursor:pointer;text-decoration: underline; color: blue;';
      //     let isNoZero = row[column.key] !== 0 ? true : false;
      //     return {
      //       style: `${isNoHzyh === true && isNoZero ? style : ''}`,
      //       class: 'cell-hover',
      //       onClick: async () => {
      //         getDetailData_4(row, index, column, isNoHzyh, isNoZero);
      //       },
      //     };
      //   },
      },
      {
        title: '剩余隐患数量（个）',
        dataIndex: 'syyhcount',
        key: 'syyhcount',
        align: 'center',
        width: 170,
		  // customCell: (row, index, column) => {
      //     let isNoHzyh = row.xzq !== '汇总' ? true : false;
      //     let style = 'cursor:pointer;text-decoration: underline; color: blue;';
      //     let isNoZero = row[column.key] !== 0 ? true : false;
      //     return {
      //       style: `${isNoHzyh === true && isNoZero ? style : ''}`,
      //       class: 'cell-hover',
      //       onClick: async () => {
      //         getDetailData_5(row, index, column, isNoHzyh, isNoZero);
      //       },
      //     };
      //   },
      },
    ],
    id: null,
    loading: true,
    keyWorld: '',
    cityToken: '', // 判断是不是市区 110000 是北京市 展示搜索宽
    currentqx: '', // 当前行政区名称
    wscolsList: [{ wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }],
  });
  // 表格的 ref Dom名称
  let { tableData, loading } = toRefs(data);
   const getCode = async () => {
    if (startTime != null && startTime != '') {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      const sTime = moment(startTime + '').format('YYYY-MM-DD');
      const eTime = moment(endTime + '').format('YYYY-MM-DD');
      const start: any = dayjs(sTime);
      const end: any = dayjs(eTime);
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      startDate.value = start;
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      endDate.value = end;
    }
  };
  async function getData() {
    const { role } = userInfo.value;
    if (startDate.value == null) {
      let currentDate = moment().format('YYYY-MM-DD');
      const start: any = dayjs(currentDate).subtract(30, 'day');
      const end: any = dayjs(currentDate);
      startDate.value = start;
      endDate.value = end;
      getTime();
    }

    console.log('****************开始时间****************', startDate.value);
    console.log('****************结束时间****************', endDate.value);

    let groupname = '';
    if (role === 'City') {
      groupname = 'qxmc';
    } else if (role === 'Area') {
      groupname = 'jzmc';
    } else if (role === 'Street') {
      groupname = 'czmc';
    }
    let params: iParams = {
      groupname: groupname,
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      xzqdm: xzqdm + '',
      towndm: towndm + '',
    };
    // console.log('@市级参数', params);
    loading.value = true;
    let res: any = await getCheckVillageProgress(params);
    console.log('@res--工作进入汇总表', res.items);

    if (res || res.items.length > 0) {
      loading.value = false;
      res.items.forEach((item: any, index: number) => {
        // item.name = selectClassFlyDict(item.xzqdm);
        item.index = index + 1;
      });
      // console.log('data', data);
      // 算列和
      let zcount = total(res.items, 'zcount');
      let jccount = total(res.items, 'jccount');
      let jcl = ((jccount / zcount) * 100).toFixed(2) + '%';
      let 合计_count = '汇总';
      let yhcount = total(res.items, 'yhcount');
      let zgcount = total(res.items, 'zgcount');
      let wjccount = total(res.items, 'wjccount');
      let wzgcount = total(res.items, 'syyhcount');
      let allObj = {
        village: 合计_count,
        zcount: zcount,
        jccount: jccount,
        jcl: jcl,
        yhcount: yhcount,
        zgcount: zgcount,
        wjccount: wjccount,
        syyhcount: wzgcount,
      };
      data.tableData = [...res.items, allObj];
    }
  }
  // 计算总数的方法
  function total(arr: any, item: any) {
    let total = arr.reduce((pre: any, cur: any) => {
      return parseInt(pre) + parseInt(cur[item]);
    }, 0);
    return total;
  }
  const getBack = () => {
    router.go(-1);
  };
  //已检查
  //已检查
  const getDetailData_1 = async (row: any) => {
    let params = {
      xzqdm: row.xzqdm,
      towndm: row.towndm,
      villagedm: row.villagedm,
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      currentTitle: '【' + row.xzq + '-' + row.town + '-' + row.village + '】未检查房屋明细',
      category: 'yjc',
    };
    router.push({
      path: 'jchourselist',
      query: params,
    });
  };
  //未检查
  const getDetailData_2 = async (row: any) => {
    let params = {
      xzqdm: row.xzqdm,
      towndm: row.towndm,
      villagedm: row.villagedm,
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      currentTitle: '【' + row.xzq + '-' + row.town + '-' + row.village + '】未检查房屋明细',
      category: 'wjc',
    };
    router.push({
      path: 'jchourselist',
      query: params,
    });
  };
  //隐患数量
  const getDetailData_3 = async (row: any) => {
    let params = {
      xzqdm: row.xzqdm,
      towndm: '',
      villagedm: '',
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      currentTitle: '【' + row.xzq + '】隐患房屋明细',
    };
    store.setData(params); // 存入Pinia
    router.push({
      path: 'balconyManager/jchourselist',
    });
  };
  //整改数量
  const getDetailData_4 = async (row: any) => {
    let params = {
      xzqdm: row.xzqdm,
      towndm: '',
      villagedm: '',
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      currentTitle: '【' + row.xzq + '】整改隐患房屋明细',
    };
    store.setData(params); // 存入Pinia
    router.push({
      path: 'workprogress/jchourselist',
    });
  };
  //剩余隐患数量
  const getDetailData_5 = async (row: any) => {
    let params = {
      xzqdm: row.xzqdm,
      towndm: '',
      villagedm: '',
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      currentTitle: '【' + row.xzq + '】剩余隐患房屋明细',
    };
    store.setData(params); // 存入Pinia
    router.push({
      path: 'balconyManager/jchourselist',
    });
  };
  function handleExport() {
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const tk = userStore.getToken;
    getTime();
    downloadByUrl({
      url:
        uriBase +
        '/village/evolvestatic/ExportExcel?access_token=' +
        tk +
        '&startTime=' +
        startDate.value.format('YYYY-MM-DD') +
        '&endTime=' +
        endDate.value.format('YYYY-MM-DD'),
      target: '_blank',
    });
  }


  function getTime() {
    data.startTime = moment(startDate.value.$d).format('YYYY-MM-DD');
    data.endTime = moment(endDate.value.$d).format('YYYY-MM-DD');
    console.log('@查询参数 -- 开始时间', data.startTime);
    console.log('@查询参数 -- 结束时间', data.endTime);
  }
  function getUserInfo() {
    const userStore = useUserStore();
    userInfo.value = userStore?.getUserInfo;
  }

  function searchBtn() {
    getTime();
    data.loading = true;
    getData();
  }

  const displayColumns = computed(() => {
    const { role } = userInfo.value;
    let arr: any[] = [];
    if (role === 'City') {
      // qx
      arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'czmc');
      return arr;
    } else if (role === 'Area') {
      // jz
      arr = data.tableColumns.filter((item) => item.key !== 'czmc' && item.key !== 'qxmc');
      return arr;
    } else if (role === 'Street') {
      // cun
      arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'qxmc');
      console.log('@Aarr', arr);
      return arr;
    } else {
      return data.tableColumns;
    }
  });
  const getTableHeight = () => {
    setTimeout(() => {
      detailTableHeight.value = window.innerHeight;
      tableHeight.value = window.innerHeight;
    });
  };
  onBeforeMount(() => {
    getUserInfo();
  });
  onMounted(() => {
    console.log('******工作进展统计初始化******');
	getCode();
    getData();
    getTableHeight();
   // getTableData();
  });
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
  #map {
    height: calc(100vh - 140px);
  }

  .x-houseMng-search {
    z-index: 100;
    margin: 6px;
    position: absolute;
  }

  .root-house-mng-main {
    margin: 6px;
  }

  .x-village-tabs {
    //z-index: 100;
    //position: absolute;
    width: 60vw;
    margin-top: 6px;
    margin-left: 40px;
    //background-color: rgba(34, 34, 34, 0.6);
    :deep(.ant-form) {
      margin-top: 6px;
    }

    // :deep(.ant-form-item-label) > label {
    //   color: white;
    // }
  }
</style>
